//
//  BeautyModelActor.swift
//  TestModelActor
//
//  Created by rolodestar on 2025/6/18.
//

import SwiftData
import Foundation

@ModelActor actor BeautyModelActor: ObservableObject{
    
    public static var shared: BeautyModelActor!
    
    public static func createShared(container: ModelContainer) -> BeautyModelActor{
        if BeautyModelActor.shared == nil{
            BeautyModelActor.shared = BeautyModelActor(modelContainer: container)
        }
        return BeautyModelActor.shared!
    }
    
    
    func save(){
            do{
                try  self.modelContext.save()
            }catch{
                print(error)
            }
        
    }
    
    func update(model: BeautyModel,by downloadStatus: BeautyModel.DownloadStatus){
        model.status = downloadStatus
        save()
    }
    
    func update(model: BeautyModel,by localUrl: URL){
        model.localUrl = localUrl
        model.status = .completed
        save()
    }
    func remove(model: BeautyModel){
        guard let m = self[ model.persistentModelID, as: BeautyModel.self]  else{ return }
        if let localUrl = m.localUrl{
            try? FileManager.default.removeItem(at: localUrl)
            
        }
    
        m.localUrl = nil
        m.status = .notStart
//        Task{@MainActor in
//        if let modelContext = model.modelContext{
//            
//            
//                modelContext.delete(model)
//                try  modelContext.save()
//            await print(self.modelContext)
//            print(modelContext)
//            }
//        }
        self.modelContext.delete(model)
        save()
        
    }
    func append(from remoteUrl: URL) {
        let model = BeautyModel(remoteUrl: remoteUrl)
        self.modelContext.insert(model)
        save()
        return 
    }
    
    func appendAndDownload(from remoteUrl: URL) {
        let model = BeautyModel(remoteUrl: remoteUrl)
        self.modelContext.insert(model)
        save()
        let downloadManager = BeautyDownloadManager(actor: self, model: model)
        Task.detached{
            await downloadManager.startDownload()
        }
//        return model
    }
    
}
